<template>
  <Spin :spinning="loading" tip="Loading...">
  <div>
    <!--紧急返件入出库管理--出库 -->
    <BreakSpace label="质量信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FormPanel ref="formPanel" :list="formList" :cols="3" :formType="'add'" labelWidth="110" :isSubmitBtn="false"
               @formChange="formChangeHandle"/>
    <div style="margin-bottom: 1rem;"></div>
    <BreakSpace label="紧急返件列表" :containerStyle="{ marginBottom: '10px' }"/>
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :datakey="'items'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :isSelectColumn="false"
      :isPagination = false
      height="auto"
    >
    </FilterTable>
    <FormPanel ref="formPanel3" :list="formList3" :cols="3" :formType="'add'" labelWidth="100" :isSubmitBtn="false"
               @formChange="formChangeHandle3"/>
    <BreakSpace label="回运信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FormPanel ref="formPanel1" :list="formList1" :cols="3" :formType="'add'" labelWidth="100" :isSubmitBtn="false"
               @formChange="formChangeHandle1"/>

    <BreakSpace label="内部领用" :containerStyle="{ marginBottom: '10px' }"/>
    <FormPanel ref="formPanel2" :list="formList2" :cols="3" :formType="'add'" labelWidth="100" :isSubmitBtn="false"
               @formChange="formChangeHandle2"/>
    <LazyLoadTab v-model="activeName" :tabMenus="menus" :destroyOnClose="true"></LazyLoadTab>
    <BaseDialog :visible.sync="supplierFlag" :title="'供应商选择'" destroyOnClose width="850px" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <SupplierList @close="supplierClose" @save="supplierSave"></SupplierList>
    </BaseDialog>
    <div style="padding-top: 3rem;"></div>
    <divd
      :style="{
        position: 'fixed',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <multiuse-button type="primary" :click="saveDialog.bind()" :disabled="this.rowData.urgentStatus==55651007?false:true">出库</multiuse-button>
      <multiuse-button type="primary" @click="closeDialog">关 闭</multiuse-button>
    </divd>
    <div style="margin-bottom: 1rem;"></div>
  </div>
  </Spin>
</template>
<script>
import {getPartType} from '@/api/claim/dealer/QualityInformationManagement_DLR/EmergencyReturn/index';
import {outStockByPtId,quyrpQaUrgent} from '@/api/claim/factory/QualityInformationManagement_OEM/CoreIssueStockInOut/index';
import { isFormEmpty } from '@/utils/index';
import SupplierList from '@/pages/claimDemage/tools/SuppliersList.vue';
import moment from "moment";
import { dictionary } from '@/utils/dictMixin';
  export default {
    mixins: [dictionary],
    props: ['rowData'],
    components: {
      SupplierList
    },
    data() {
      return {
        loading: false,
        editRow: {},
        dataList: [],
        dtlIdVal: 0,
        collapse: false,
        supplierFlag: false,
        urgentStatusFlag: 5,
        infoId: null,
        fetchParams: {}, //ipa 接口
        selectedRows: [], //选中经销商
        formList: this.createFormList(),
        formList1: this.createFormList1(),
        formList2: this.createFormList2(),
        formList3: this.createFormList3(),
        columns: this.creatHeader(),
        saveData: null,
        activeName: '出库记录',
        menus: [
          {
            title: '出库记录',
            path: 'claimDemage/QualityInformationManagement_OEM/CoreIssueStockInOut/StockLog/StockLog',
            params: {
              type: 1,
              urgentId:this.rowData.urgentId
            }
          },

        ]
      };
    },
    async created() {
      this.loading = true;
      await this.chuqi();
      await this.getDetailFun(this.rowData.urgentId);
      this.loading = false;
    },
    methods: {
      supplierSave(val) {
        this.$refs.table.$refs.pageTable.list.map(x => {
          console.log(x.dtlId);
        if(x.dtlId==this.dtlIdVal){
          console.log(val[0].supCode);
          x.supName= val[0].supName;
          x.supNo= val[0].supCode;
          console.log(x.supNo);
        }
        });
        this.supplierFlag=false;
      },
      supplierClose(val) {
        this.supplierFlag=false;
      },
      getSupplierFun(val){
        this.dtlIdVal=val.dtlId
        this.supplierFlag=true;
      },
      //考核类型
      async chuqi() {
        // const res3 = await getPartType({type: 5564});
        // if (res3.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'dataSource').itemList = res3.data.map(y => ({
        //     text: y.codeCnDesc,
        //     value: y.codeId
        //   }));
        // }
        // const res4 = await getPartType({type: 5565});
        // if (res4.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'urgentStatus').itemList = res4.data.map(y => ({
        //     text: y.codeCnDesc,
        //     value: y.codeId
        //   }));
        // }
        // const res5 = await getPartType( {type:5500});
        // if (res5.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'isKeep').itemList = res5.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
        // }
      },
      async getDetailFun(val) {
        let res= await quyrpQaUrgent({id : val});
        this.editRow = res.data;
        if(res.data.saleDate){
          res.data.saleDate = moment(res.data.saleDate).format('YYYY-MM-DD');
        }
        if(res.data.prodDate){
          res.data.prodDate = moment(res.data.prodDate).format('YYYY-MM-DD');
        }
        //为form赋值
        for (let i in res.data) {
          this.formList.map(x => {
            if (x.fieldName == i) {
              x.initialValue = res.data[i];
            }
          });
        }
        for (let i in res.data) {
          this.formList1.map(x => {
            if (x.fieldName == i) {
              x.initialValue = res.data[i];
            }
          });
          this.formList1.forEach(x => {
            x.initialValue = res.data[x.fieldName];
            if (x.fieldName == 'fileList') {
              x.initialValue = res.data.fileList.map((f) => ({ name: f.title, url: f.fileUrl }));
            }
          });
        }
        for (let i in res.data) {
          this.formList2.map(x => {
            if (x.fieldName == i) {
              x.initialValue = res.data[i];
            }
          });
        }
        for (let i in res.data) {
          this.formList3.map(x => {
            if (x.fieldName == i) {
              x.initialValue = res.data[i];
            }
          });
          this.formList3.forEach(x => {
            x.initialValue = res.data[x.fieldName];
            if (x.fieldName == 'fileList') {
              x.initialValue = res.data.fileList.map((f) => ({ name: f.title, url: f.fileUrl }));
            }
          });
        }
        let fileIds = [];
        res.data.fileList.map(x =>{
          fileIds.push(x.fileId);
        });
        let idsss = '';
        fileIds.map(x => {
          idsss += x + ','
        });
        this.fileIds = idsss;
        //为table赋值
        if (200 == res.resultCode) {
          let data = res.data;
          if (isFormEmpty(data)) {
            data = {};
          }
          let records = data.dtlList;
          console.log(records);
          if (isFormEmpty(records)) {
            records = [];
          }
          this.$refs.table.$refs.pageTable.EXECUTE_INSERT(records);
        }
      },
      formChangeHandle(val) {
        this.saveData1 = val;
      },formChangeHandle1(val) {
        this.saveData1 = val;
      },
      formChangeHandle2(val) {
        this.saveData2 = val;
      },formChangeHandle3(val) {
        this.saveData3 = val;
      },
      //搜索获取数据
      changeHandle(val) {
        this.fetchParams = val;
        console.log(val);
      },
      //选中
      selectChange(rows) {
        this.selectedRows = rows;
        console.log(this.selectedRows);
      },
      //保存
      async saveDialog() {
        this.$refs.formPanel2.SUBMIT_FORM();
        if (this.saveData2) {

          let arr = [];
          this.$refs.table.$refs.pageTable.list.map(x => {
            arr.push(x);
          });
          this.editRow.dtlList = arr;
          this.editRow = Object.assign(this.editRow, this.saveData2);
          let fileList = [];
          this.editRow.fileList.map((x) => {
            fileList.push({title: x.name, fileUrl: x.url});
          });
          this.editRow.delFileIds = this.fileIds;
          this.editRow.fileList = fileList;
          this.editRow.urgentId = this.rowData.urgentId;
          this.editRow.stockStatus = 55691001;
          let flag = false;
          this.$refs.table.$refs.pageTable.list.map(x => {
            if (x.supCode) {
              flag = true;
            }
          });
          let istable = this.$refs.table.$refs.pageTable.GET_REQUIRED_ERROR();
          if (istable) {
            this.number = 1;
          } else {
            this.number = 2;
          }
          if (this.editRow.phone || this.editRow.pickBy || this.editRow.outRemarks && flag) {
            return this.$notify.warning({title: '提示信息', message: '供应商和内部领用不能同时填写'});

          } else if(this.number == 2){
            this.loading = true;
            let res = await outStockByPtId(this.editRow);
            console.log(res);
            if (res.resultCode === 200) {
              this.$emit('save');
              return this.$notify.success({title: '提示信息', message: '保存成功'});
            } else {
              this.loading = false;
              // this.$notify.error({title: '提示信息', message: res.errMsg || '保存失败!'});
              // this.closeDialog();
            }
          }
        }else{
          this.loading = false;
          return this.$notify.warning({title: '提示信息', message: '有未校验通过的信息'});
        }
      },
      //取消操作
      closeDialog() {
        this.$emit('close', {visible: false, data: this.selectedRows, type: 'close'});
      },
      //紧急返件列表
      creatHeader() {
        return [
          {
            title: '序号',
            dataIndex: 'index',
            width: 80,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          }, {
            title: '操作',
            dataIndex: 'supNo1',
            render: props => {
              return (
                <div>
                <multiuse-button size="mini" type="text" onClick={() => this.getSupplierFun(props.row)}>
              选择供应商
              </multiuse-button>
              </div>
            );
            }
          },
          { title: '配件代码', dataIndex: 'partCode', sorter: true },
          { title: '配件名称', dataIndex: 'partName', sorter: true },
          { title: '单位', dataIndex: 'partUnit', sorter: true },
          { title: '回运数量', dataIndex: 'partCount', sorter: true },
          { title: '入库数量', dataIndex: 'inCount', sorter: true },
          { title: '旧件状态', dataIndex: 'statusStr', sorter: true },
          { title: '出库数量', dataIndex: 'outCount', editable: true,
            defaultEditable: true,
            showOverflowTooltip: true,
            editType: 'number',
            editRequired: true,
            editValidator:(val, row, callback) => {
              if (row.outCount > row.inCount) {
                this.$notify.error({ title: '提示信息', message: '已超过入库最大数量(' + row.inCount + ')' || '操作失败!' });
                row.outCount = 0
              }
            }

          },
         {
            title: '供应商代码',
            dataIndex: 'supNo',
            sorter: true
          },
          { title: '供应商名称', dataIndex: 'supName', sorter: true },
          { title: '收件人', dataIndex: 'receiver', sorter: true },
          { title: '收件人电话', dataIndex: 'receiverTel', sorter: true },
          { title: '入库说明', dataIndex: 'inRemarks', sorter: true },
          { title: '收件地址', dataIndex: 'receiverAddress', sorter: true }
        ];
      },
      //质量信息
      createFormList() {
        return [
          {
            type: 'INPUT',
            label: '紧急返件单号',
            fieldName: 'urgentNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '质量报告单号',
            fieldName: 'reportNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'SELECT',
            label: '数据来源',
            fieldName: 'dataSource',
            readonly: true,// 只读
            disabled: true, // 置会
            itemList: this.createDictList('5564'),
          },
          {
            type: 'INPUT',
            label: '经销商代码',
            fieldName: 'dealerCode',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '经销商名称',
            fieldName: 'dealerName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'SELECT',
            label: '紧急返件单状态',
            fieldName: 'urgentStatus',
            readonly: true,// 只读
            disabled: true, // 置会
            itemList: this.createDictList('5565'),
          },
          {
            type: 'INPUT',
            label: '维修工单号',
            fieldName: 'roNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: 'VIN',
            fieldName: 'vin',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '索赔单号',
            fieldName: 'cmsClaimNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '生产日期',
            fieldName: 'prodDate',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '销售日期',
            fieldName: 'saleDate',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '行驶里程',
            fieldName: 'driveMile',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '维修开始时间',
            fieldName: 'serviceBeginDate',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '主损件',
            fieldName: 'partCode',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '主损件名称',
            fieldName: 'partName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '维修结束时间',
            fieldName: 'serviceEndDate',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '故障现象代码',
            fieldName: 'faultCode',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '故障现象描述',
            fieldName: 'faultName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '车型名称',
            fieldName: 'modelName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'SELECT',
            label: '是否留车',
            fieldName: 'isKeep',
            placeholder: '请输入...',
            disabled:true,
            itemList: this.createDictList('5500'),
          },
          {
            type: 'INPUT',
            label: '留车单号',
            fieldName: 'keepCar',
            placeholder: '请输入数量...',
            disabled: true, // 置会
          },
        ];
      },
      createFormList1() {
        return [
          {
            type: 'INPUT',
            label: '物流单号',
            fieldName: 'expressNo',
            disabled:true,
            // rules: [{required: true, message: '请输入物流公司', trigger: 'change'}]
          },
          {
            type: 'INPUT',
            label: '邮寄人',
            fieldName: 'expressUser',
            disabled:true,
            // rules: [{required: true, message: '请输入物流公司', trigger: 'change'}]
          }, {
            type: 'INPUT',
            label: '邮寄人电话',
            fieldName: 'expressTel',
            disabled:true,
            // rules: [{required: true, message: '请输入物流公司', trigger: 'change'}]
          },{
            type: 'INPUT',
            label: '回运时间',
            fieldName: 'expressDate',
            disabled:true,
            // rules: [{required: true, message: '请输入物流公司', trigger: 'change'}]
          },{
            type: 'TEXT_AREA',
            label: '邮寄说明',
            disabled:true,
            fieldName: 'expressRemarks',
            initialValue: '',
            selfCols: 3,// 元素占据几行
            rows: 3,
            placeholder: '请输入数量...'
          },
          {
            type: 'UPLOAD_FILE',
            label: '上传文件',
            fieldName: 'fileList',
            placeholder: '上传文件...',
            initialValue: [],
            disabled: true,
            upload: {
              actionUrl: '/api/file/oss/upload',
              limit: 2,
              // tipText: '只能上传pdf格式'
            }
          },
          {
            type: 'TEXT_AREA',
            label: '入库说明',
            disabled:true,
            fieldName: 'expressRemarks',
            selfCols: 3,// 元素占据几行
            rows: 3
          },
        ];
      },
      createFormList2() {
        return [
          {
            type: 'INPUT',
            label: '领件人',
            fieldName: 'pickBy',
            // rules: [{required: true, message: '请输入物流公司', trigger: 'change'}]
          },
          {
            type: 'INPUT',
            label: '联系电话',
            fieldName: 'phone',
            // rules: [{required: true, message: '请输入物流单号', trigger: 'change'}]
          },
          {
            type: 'TEXT_AREA',
            label: '出库说明',
            fieldName: 'outRemarks',
            selfCols: 3,// 元素占据几行
            rows: 2
          },
        ];
      },
      createFormList3() {
        return [
          {
            type: 'TEXT_AREA',
            label: '返件要求说明',
            disabled:true,
            fieldName: 'urgentRemarks',
            selfCols: 3,// 元素占据几行
            rows: 1
          },
        ];
      },

    }
  };
</script>

<style lang="less" scoped></style>
